package com.rzico.sbl.ui.order

import android.os.Bundle
import android.os.PersistableBundle
import android.view.MotionEvent
import androidx.core.view.isVisible
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CustomMapStyleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.setAnimateCamera
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderShipBinding
import com.rzico.sbl.other.OrderService
import com.rzico.sbl.other.serviceId
import com.rzico.sbl.ui.manager.MasterMapActivity
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.clear
import com.xinnuo.common_ui.utils.showActionDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import org.json.JSONObject

class OrderShipActivity : BaseActivity(R.layout.activity_order_ship) {

    private val mBinding by lazy { ActivityOrderShipBinding.bind(getRootView()) }

    // 订单信息
    private lateinit var mOrderSn: String
    private var mCardId = ""
    private var mMemberId = ""
    private var mShipMethodId = ""
    private var mSellerId = ""
    private var mEnterpriseId = ""
    private var mSellerOwnerId = ""

    // 收货信息
    private var mReceiveName = ""
    private var mReceivePhone = ""
    private var mReceiveLat = ""
    private var mReceiveLng = ""
    private var mReceiveAdress = ""

    // 配送站点、人员
    private var mShopId = ""
    private var mShopLat = ""
    private var mShopLng = ""
    private var mAdminId = ""
    private var mAdminName = ""
    private var mAdminPhone = ""

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        initTitle(title = "确认发货")

        initAmap()

        getData()
    }

    private fun initAmap() {
        mBinding.shipMap.map.apply {
            uiSettings.apply {
                isZoomControlsEnabled = false     //缩放按钮，默认打开
                isCompassEnabled = false          //指南针，默认不显示
                isMyLocationButtonEnabled = false //定位按钮
                isScaleControlsEnabled = true     //比例尺
                isScrollGesturesEnabled = true    //滑动手势
                isZoomGesturesEnabled = true      //缩放手势
                isRotateGesturesEnabled = true    //旋转手势
                isTiltGesturesEnabled = false      //倾斜手势
                logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT //地图logo显示在右下方
            }

            mapType = AMap.MAP_TYPE_NAVI   //导航地图模式
            isTrafficEnabled = true        //实时交通状况
            showBuildings(false)           //显示3D楼块
            showMapText(true)              //显示底图文字
            showIndoorMap(false)           //设置是否显示室内地图
            isMyLocationEnabled = false    //触发定位并显示定位层

            // 自定义地图
            setCustomMapStyle(
                CustomMapStyleOptions().apply {
                    isEnable = true
                    styleData = getByteFromAssets("style.data")
                    styleExtraData = getByteFromAssets("style_extra.data")
                }
            )

            // 地图触摸监听
            setOnMapTouchListener {
                mBinding
                    .shipScroll
                    .requestDisallowInterceptTouchEvent(
                        it.action != MotionEvent.ACTION_UP
                    )
            }

            // 默认显示郑州经纬度
            moveCamera(
                CameraUpdateFactory
                    .newLatLng(LatLng(34.7466, 113.625367))
            )
        }
    }

    override fun initListener() {
        mOrderSn = intent.getExtra("orderSn")

        mBinding.apply {
            // 结算金额设置
            shipSettle
                .filters =
                arrayOf(
                    DecimalNumberFilter(),
                    NameLengthFilter(8)
                )

            // 会员详情
            shipMemberLl.oneClick {
                (mCardId.isNotEmpty()
                        && mMemberId.isNotEmpty())
                    .condition {
                        startActivityEx<MemberDetailActivity>(
                            "cardId" to mCardId,
                            "memberId" to mMemberId
                        )
                    }
            }

            // 配送方式
            shipWay.oneClick {
                showActionDialog(
                    "普通快递", "同城配送", "到店自提"
                ) { index, hint ->
                    mShipMethodId = when (index) {
                        0 -> "shipping"
                        1 -> "warehouse"
                        2 -> "pickup"
                        else -> ""
                    }

                    shipWay.setRightString(hint)

                    shipWhere.isVisible = mShipMethodId != "pickup"
                    shipWho.isVisible = mShipMethodId != "pickup"
                    optionLocation()
                }
            }

            // 配送站点
            shipWhere.oneClick {
                // 经纬度为空时，不显示距离
                startActivityEx<OrderShipWhereActivity>(
                    "lat" to mReceiveLat,
                    "lng" to mReceiveLng
                )
            }

            // 实时位置
            shipLocation.oneClick {
                startActivityEx<MasterMapActivity>(
                    "from" to "ship",
                    "receiveName" to mReceiveName,
                    "receivePhone" to mReceivePhone,
                    "receiveLat" to mReceiveLat,
                    "receiveLng" to mReceiveLng,
                    "receiveAdress" to mReceiveAdress
                )
            }

            // 配送人员
            shipWho.oneClick {
                mShopId.ifEmpty {
                    showToast("请选择发货仓库")
                    return@oneClick
                }

                startActivityEx<OrderShipWhoActivity>("shopId" to mShopId)
            }

            // 确认发货
            btShip.oneClick {
                when {
                    mShopId.isEmpty()
                            && mShipMethodId != "pickup" -> {
                        showToast("请选择发货仓库")
                        return@oneClick
                    }

                    mAdminId.isEmpty()
                            && mShipMethodId != "pickup"
                            && mSellerId == mSellerOwnerId -> {
                        showToast("请选择发货人员")
                        return@oneClick
                    }

                    shipSettleLl.isVisible
                            && serviceId in OrderService.UNION_CONTROL
                            && shipSettle.content.isEmpty() -> {
                        showToast("请输入结算金额")
                        return@oneClick
                    }
                }

                getViewModel()
                    .shipOrder(
                        orderSN = mOrderSn,
                        method = mShipMethodId,
                        shopId = mShopId,
                        adminId = mAdminId,
                        transfer = mSellerId != mSellerOwnerId,
                        price = shipSettle.content,
                        memo = shipMemo.textTrim
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单发货成功！")

                            intent
                                .getIntExtra("index", -1)
                                .also {
                                    (it > -1).conditionElse(
                                        actionTrue = {
                                            // 更新订单列表
                                            LiveEventBus
                                                .get("orderList")
                                                .post("refresh")
                                        },
                                        actionFalse = {
                                            // 更新订单列表
                                            LiveEventBus
                                                .get("orderWarn")
                                                .post("refresh")
                                        }
                                    )
                                }

                            // 更新发货地图
                            LiveEventBus
                                .get("orderShipMap")
                                .post("update")

                            // 更新批量订单列表
                            LiveEventBus
                                .get("batchList")
                                .post("refresh")

                            // 更新订单详情
                            LiveEventBus
                                .get("orderDetail")
                                .post("refresh")

                            finishView()
                        }
                    )

            }
        }

        // 站点、人员监听
        observe<String>("orderShip") { result ->
            val items = result.split(",")
            when (items[0]) {
                "shop" -> {
                    (mShopId != items[1])
                        .condition {
                            mShopId = items[1]
                            mEnterpriseId = items[3]
                            mSellerOwnerId = items[4]
                            mShopLat = items[5]
                            mShopLng = items[6]

                            mAdminId = ""
                            mAdminName = ""
                            mAdminPhone = ""

                            mBinding.apply {
                                // 发货仓库
                                shipWhere.setRightString(items[2])
                                // 送货人员
                                shipWho.setRightHintString(
                                    (mSellerId == mSellerOwnerId)
                                        .conditionElseValue(
                                            actionTrue = { "请选择送货人员" },
                                            actionFalse = { "请选择送货人员(选填)" }
                                        )
                                )
                                shipWho.setRightString("")

                                // 地图位置
                                optionLocation()
                                // 结算金额
                                optionSettlePrice()
                            }
                        }
                }

                "admin" -> {
                    mAdminId = items[1]
                    mAdminName = items[2]
                    mAdminPhone = items[3]

                    mBinding
                        .shipWho
                        .setRightString(
                            mAdminName + mAdminPhone.ifNotEmpty { " - $it" }
                        )
                }
            }
        }
    }

    /**
     * 判断实时位置显隐
     */
    private fun optionLocation() {
        // 实时位置
        mBinding
            .shipLocation
            .isVisible = mShipMethodId == "warehouse"
                && mSellerId == mSellerOwnerId
                && mReceiveLat.isNotEmpty()
                && mReceiveLng.isNotEmpty()

        // 地图打点
        (mShipMethodId == "warehouse"
                && mReceiveLat.isNotEmpty()
                && mReceiveLng.isNotEmpty())
            .apply {
                mBinding
                    .shipMapRl
                    .isVisible = this
            }
            .condition {
                getViewModel()
                    .delay {
                        animateMapMarker()
                    }
            }
    }

    /**
     * 判断结算金额显隐
     */
    private fun optionSettlePrice() {
        mBinding.apply {
            shipSettleLl.isVisible = mSellerId != mSellerOwnerId

            shipSettle.hint =
                (shipSettleLl.isVisible
                        && serviceId in OrderService.UNION_CONTROL)
                    .conditionElseValue(
                        actionTrue = { "请输入结算金额" },
                        actionFalse = { "请输入结算金额(选填)" }
                    )

            shipSettle.clear()
        }
    }

    private fun animateMapMarker() {
        mBinding.shipMap.map.apply {
            clear()

            val bounds = LatLngBounds
                .Builder()
                .apply {
                    (mShopLat.isNotEmpty()
                            && mShopLng.isNotEmpty())
                        .condition {
                            include(
                                LatLng(
                                    mShopLat.doubleValue,
                                    mShopLng.doubleValue
                                )
                            )
                        }

                    (mReceiveLat.isNotEmpty()
                            && mReceiveLng.isNotEmpty())
                        .condition {
                            include(
                                LatLng(
                                    mReceiveLat.doubleValue,
                                    mReceiveLng.doubleValue
                                )
                            )
                        }
                }
                .build()

            setAnimateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100)) {
                onFinish {
                    (mShopLat.isNotEmpty()
                            && mShopLng.isNotEmpty())
                        .condition {
                            addMarker(
                                MarkerOptions()
                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_manager22))
                                    .position(
                                        LatLng(
                                            mShopLat.doubleValue,
                                            mShopLng.doubleValue
                                        )
                                    )
                            )
                        }

                    (mReceiveLat.isNotEmpty()
                            && mReceiveLng.isNotEmpty())
                        .condition {
                            addMarker(
                                MarkerOptions()
                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_manager23))
                                    .position(
                                        LatLng(
                                            mReceiveLat.doubleValue,
                                            mReceiveLng.doubleValue
                                        )
                                    )
                            )
                        }
                }
            }
        }
    }

    /**
     * 获取订单详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .viewOrder(mOrderSn)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)
                    mCardId = obj.optNotNull("cardId")
                    mMemberId = obj.optNotNull("memberId")
                    mShipMethodId = obj.optNotNull("shippingMethodId")
                    mSellerId = obj.optNotNull("sellerId")
                    mEnterpriseId = obj.optNotNull("enterpriseId")
                    mSellerOwnerId = mSellerId

                    (mShipMethodId != "pickup")
                        .condition {
                            mShopId = obj.optNotNull("shopId")
                            mShopLat = obj.optNotNull("shopLat")
                            mShopLng = obj.optNotNull("shopLng")
                            mAdminId = obj.optNotNull("adminId")
                            mAdminName = obj.optNotNull("adminName")
                            mAdminPhone = obj.optNotNull("adminPhone")
                        }

                    val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                    mReceiveName = objReceive.optNotNull("consignee")
                    mReceivePhone = objReceive.optNotNull("phone")
                    mReceiveLat = objReceive.optNotNull("lat")
                    mReceiveLng = objReceive.optNotNull("lng")
                    mReceiveAdress = objReceive.optNotNull("address")

                    mBinding.apply {
                        val orderMethod = obj.optNotNull("orderMethod")

                        shipBorrow.text = obj.optNotEmpty("borrow", "0")
                        shipArrear.text = obj.optNotNull("arrears").formatDecimal()

                        // 订单类型
                        shipType.text =
                            orderMethod.run {
                                notEmpty { shipTypeLl.visible() }

                                when (this) {
                                    "online" ->
                                        when (obj.optNotNull("paymentPluginId")) {
                                            "ticketPayPlugin" -> "货到付款"
                                            else -> "线上订单"
                                        }

                                    "ali" ->
                                        when (obj.optNotNull("paymentPluginId")) {
                                            "ticketPayPlugin" -> "货到付款"
                                            else -> "支付宝"
                                        }

                                    "offline" -> "人工报单"
                                    "history" -> "人工补单"
                                    "nongfu" -> "农夫APP"
                                    "meituan" -> "美团"
                                    "eleme", "elemengc" -> "饿了么"
                                    "jd" -> "京东"
                                    "taobao" -> "淘宝"
                                    "pinduoduo" -> "拼多多"
                                    "dummy" -> "自提点"
                                    else -> "其他"
                                }
                            }
                        // 支付状态
                        shipMethod.text =
                            when (orderMethod) {
                                "offline" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    obj.optNotNull("payMethod")
                                                        .run {
                                                            isEmpty()
                                                                .conditionElseValue(
                                                                    actionTrue = {
                                                                        shipMethodLl.visible()
                                                                        "未支付"
                                                                    },
                                                                    actionFalse = { "已支付" }
                                                                )
                                                        }
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                "online", "ali" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    shipMethodLl.visible()
                                                    "未支付"
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                else -> "已支付"
                            }

                        // 发货方式
                        shipWay.setRightString(
                            when (mShipMethodId) {
                                "shipping" -> "普通快递"
                                "warehouse" -> "同城配送"
                                "pickup" -> "到店自提"
                                else -> ""
                            }
                        )

                        shipWhere.isVisible = mShipMethodId != "pickup"
                        shipWho.isVisible = mShipMethodId != "pickup"

                        // 发货仓库
                        mShopId.notEmpty {
                            shipWhere.setRightString(
                                obj.optNotNull("shopName")
                            )
                        }

                        // 送货人员
                        mAdminId.notEmpty {
                            shipWho.setRightString(
                                mAdminName + mAdminPhone.ifNotEmpty { " - $it" }
                            )
                        }

                        // 地图位置
                        optionLocation()
                    }

                }
            )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mBinding.shipMap.onCreate(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        // onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.shipMap.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        // onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.shipMap.onResume()
    }

    override fun onPause() {
        super.onPause()
        // onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.shipMap.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.shipMap.onDestroy()
    }

}